/**
 * 通用工具助手
 */
import $store from '@/store'
import uniApi from '@/util/uniApi'
import {baseUrl} from '../config'
// import { SCENE_PAGE_MAP } from '@/enums/const'
import { queryStringify } from '@/util/lib/pageUtil'
// import { getqrcode } from '@/api/app'
import util, { bShopInit } from '@/util'

// 是否是微信浏览器
export function isWxBrowser() {
	const ua = navigator.userAgent.toLowerCase()
	if (ua.match(/MicroMessenger/i) === 'micromessenger') {
		return true
	} else {
		return false
	}
}


/**
 * 生成二维码
 * @param {any} str 二维码内容
 * @param {Number} qrType = 1 1:方块 2:条形码
 * @param {Number} width = 109
 * @param {Number} height = 109
 */
export function qrCode(str = '', qrType = 1, width = 109, height = 109) {
	if (typeof str === 'object') {
		str = JSON.stringify(str)
	}
	const url = `${baseUrl.baseUrl}${baseUrl.context}/order/qr_codes?str=${str}&qrType=${qrType}&width=${width}&height=${height}`
	return encodeURI(url)
}

/**
 * 校验手机号
 */
export function verifyPhone(phone = '') {
	let reg = /^[1][0-9]{10}$/
	if (!phone) {
		return false
	} else if (!reg.test(phone)) {
		return false
	} else {
		return true
	}
}

/**
 * TODO
 * 生成二维码
 * @param scene
 * @param path
 * @param width
 * @returns {string}
 */
export async function scene2Qr(scene, path = 'pages/index/index', width = 500) {
	const shareInfo = await sharePath(scene)
	return new Promise(async (resolve, reject) => {
		try {
			const { data = '' } = await getqrcode({
				page: path,
				pageType: 0,
				scene: shareInfo,
				width
			})
			return resolve(data)
		} catch (error) {
			console.log('错误信息:', error)
		}
	})
}

// 解析二维码
export function parseQrCode(scene) {
	let infoIdx = scene.lastIndexOf('=')
	let sceneInfo = scene.substring(infoIdx + 1, scene.length)
	let id = sceneInfo
	getqrcodescene({ id }).then(async ({ data }) => {
		if (!data) return
		await codeNew(data)

		await bShopInit()
	})
}

function codeNew(data) {
	let index = data.indexOf('?') || 0
	let urlName = data.substring(0, index)
	let sceneName = data.substring(index + 1, data.length)
	uniApi.pageNav({ url: `${SCENE_PAGE_MAP[urlName]}?${sceneName}` })

	let skIndex = data.indexOf('sk=')
	if (skIndex !== -1) {
		let sk = data.substring(skIndex + 3, data.length)
		console.log('sk', sk)
		$store('app').setSK(sk)
	}
	let codeIndex = data.indexOf('invitationCode=')
	if (codeIndex !== -1) {
		console.log('codeIndex', codeIndex)
		let code = data.substring(codeIndex + 15, codeIndex + 20)
		console.log('code', code)
		$store('app').setInviteCode(code)
	}
}

// 查询参数转换为字符串形式，并返回转换后的url
async function sharePath(url = '') {
	let query = ''
	let path = ''
	query = url
	for (let key in SCENE_PAGE_MAP) {
		if (query.page === SCENE_PAGE_MAP[key]) {
			path = key
		}
	}
	delete query.page
	console.log('获取参数=:', query)
	// 键值对格式 转化为 字符串形式的参数
	query = queryStringify(query)
	url = `${path}?${query}`
	console.log('分享出去的参数:', url)
	return url
}

// 判断当前环境
// 1-微信小程序 2-安卓 3-IOS // 有其他需要自行添加
export function getSource() {
	let source

	// #ifdef MP-WEIXIN
	source = 1
	// #endif

	//#ifdef APP-PLUS
	uni.getSystemInfo({
		success(res) {
			if (res.osName == 'ios') {
				source = 3
			} else {
				source = 2
			}
		}
	})
	//#endif

	return source
}

/**
 * 普通二维码 - 非小程序二维码
 * 解析并重新组装普通二维码中带过来的参数
 * scancode_time, q 特有字段
 */
export function getNormalQrCode(params) {
	const { scancode_time = '', q = '' } = params.query
	if (scancode_time && q) {
		let newQuery = decodeURIComponent(q)
		let domainIdx = Number(newQuery.indexOf('//'))
		let domainUrl = newQuery.substring(domainIdx + 2, newQuery.length)
		let idx = Number(domainUrl.indexOf('/'))
		let url = domainUrl.substring(idx, domainUrl.length)
		// if (url.indexOf('?') !== -1) {
		// 	params.query.url = url
		// }
		// 判断链接是否有参数
		if (url.indexOf('?') !== -1) {
			params.query.url = url + '&parameter=1'
		} else {
			params.query.url = url + '?parameter=1'
		}
	}
	return params
}

// 根据字符串中的key获取key对应的参数
export function getQueryValueByKey(key, url) {
	let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
	let result = url.match(reg)
	return result ? decodeURIComponent(result[2]) : null
}
